package com.lc.projects.unit.thread.part06.test1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;

//非阻塞式线程安全列表 ConcurrentLinkedDeque
public class Test2 {
	public static void main(String[] args) {
		ConcurrentLinkedDeque<String> list = new ConcurrentLinkedDeque<>();
		List<String> list2 = new ArrayList<>();

		Thread[] threads = new Thread[100];
		for (int i = 0; i < threads.length; i++) {
			AddTask task = new AddTask(list, list2);
			threads[i] = new Thread(task);
			threads[i].start();
		}

		System.out.println("Main:add Task Threads has been launched.");

		for (int i = 0; i < threads.length; i++) {
			try {
				threads[i].join();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < threads.length; i++) {
			PollTask task = new PollTask(list, list2);
			threads[i] = new Thread(task);
			threads[i].start();
		}

		for (int i = 0; i < threads.length; i++) {
			try {
				threads[i].join();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		System.out.println("Main:List size:" + list.size() + " " + list2.size());
	}
}

class AddTask implements Runnable {
	private ConcurrentLinkedDeque<String> list;
	private List<String> list2;

	public AddTask(ConcurrentLinkedDeque<String> list, List<String> list2) {
		super();
		this.list = list;
		this.list2 = list2;
	}

	@Override
	public void run() {
		String name = Thread.currentThread().getName();
		for (int i = 0; i < 10000; i++) {
			list.add(name + ":Element " + i);
		//	list2.add(name + ":Element " + i);
		}
	}

}

class PollTask implements Runnable {
	private ConcurrentLinkedDeque<String> list;
	private List<String> list2;

	public PollTask(ConcurrentLinkedDeque<String> list, List<String> list2) {
		super();
		this.list = list;
		this.list2 = list2;
	}

	@Override
	public void run() {
		for (int i = 0; i < 5000; i++) {
			list.pollFirst();
			list.pollLast();
			try {
			//	list2.remove(0);
			//	list2.remove(list2.size());
			} catch (Exception e) {
				System.out.println("-----------" );
				e.printStackTrace();
			}
		}
	}

}